package oocl.ita.eordering.webService;

import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

import javax.ws.rs.core.MediaType;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.WebResource;

import oocl.ita.eordering.po.Merchant;
import oocl.ita.eordering.service.FoodService;
import oocl.ita.eordering.service.MerchantService;

@Component
public class GetMerchantPassWS {
	@Autowired(required = true)
	private MerchantService mService;
	@Autowired(required = true)
	private FoodService fService;

	public FoodService getfService() {
		return fService;
	}

	public void setfService(FoodService fService) {
		this.fService = fService;
	}

	public MerchantService getmService() {
		return mService;
	}

	public void setmService(MerchantService mService) {
		this.mService = mService;
	}

	private Properties prop = new Properties();

	public List<Merchant> getMechantPass() {
		Client client = Client.create();
		client.setReadTimeout(1000);
		System.out.println("prop" + prop);
		try {
			String fileUrl = GetMerchantPassWS.class.getResource("/ws.properties").getPath();
			System.out.println("url:" + fileUrl);
			prop.load(new FileInputStream(fileUrl));
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		String url = prop.getProperty("statUrlforMerchant");

		WebResource wr = client.resource(url);
		String mPassIds = wr.accept(MediaType.APPLICATION_JSON_TYPE)// accept请求头
				.get(String.class);
		System.out.println("mPassIds list is ..." + mPassIds);
		mPassIds = mPassIds.substring(0, mPassIds.length() - 1);
		System.out.println("mPassIds substring..." + mPassIds);
		String[] mpIds = mPassIds.split(",");
		for (String string : mpIds) {
			System.out.println(string);
		}
		// midToMerchants(mpIds);
		List<Merchant> merchants = midToMerchants(mpIds);
		System.out.println(".............."+merchants.size());
		return merchants;
	}

	@SuppressWarnings("unused")
	public List<Merchant> midToMerchants(String[] mpIds) {
		List<Merchant> merchantsPass = new ArrayList<Merchant>();
		List<Merchant> merchants = mService.findAllMerchant();
		System.out.println("before:" + merchants.size());
		for (Merchant merchant : merchants) {

			for (int i = 0; i < mpIds.length; i++) {
				if (mpIds[i].equals(merchant.getmId().toString())) {
					if (fService.findFoodByMerchantId(merchant.getmId()) != null)
						merchantsPass.add(merchant);
					break;
				}
			}
		}
		if (merchantsPass != null) {
			System.out.println("after:" + merchantsPass.size());
			return merchantsPass;
		} else {
			System.out.println("....");
			return null;
		}
	}
}
